<template>
  <div class="list-view">
    <XcTable class="is-list" ref="tableView" :tableKey="$route.path" v-model:keywords="query.keyword"
      v-model:page="query.pageIndex" v-model:limit="query.pageSize" :pageTotal="total" :config="tableConfig"
      :state="state" :values="tableData" :formRef="queryFormRef" operationWidth="180px"
      :pagingConfig="{ background: true }" @update="getList">
      <template #default="{ row }">
        <el-link size="small" type="primary" :underline="false" @click="detailModel.showForm(row)">编辑</el-link>
        <el-link v-if="row.account !== 'admin'" size="small" type="danger" :underline="false"
          @click="onDelete(row)">删除</el-link>
      </template>
      <template #actions>
        <div class="filter-view">
          <el-button type="primary" :icon="Plus" @click="detailModel.showForm()">新建用户</el-button>
          <XcForm :config="queryFilterConfig" ref="queryFormRef" isQueryFilter @submit="queryFilter"></XcForm>
        </div>
      </template>
    </XcTable>
    <AddDialog v-model="detailModel.formVisible.value" :detail="detailModel.activeItem.value" :roles="roles"
      @update="detailModel.onFormUpdate"></AddDialog>
  </div>
</template>

<script setup lang="ts">

import { useUserStore } from "../store/userStore";

const dataEvent = (data: any) => {
  console.log("子组件收到数据了", data);
}

defineExpose({
  dataEvent
})

// 2. 实例化组合式 store
const userStore = useUserStore();

// 验证存储结果
console.log("存储后 Pinia 中的值：", userStore.sendUserCmd);


import { getUsersByCondition, getRoles, deleteUser } from "../api/user/index";
import type { UserItem } from "../api/user/index.d";

import { onMounted, ref } from "vue";
import type { ColumnItem as TableConfig } from "@xc-components/xc-table/types";
import type { ColumnItem as FormConfig, XcFormInstance } from "@xc-components/xc-form/types";
import AddDialog from "./components/AddDialog.vue";
import type { OptionItem } from "../api/index.d";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Search } from "@element-plus/icons-vue";
// import { useRouter } from "vue-router";
// const router = useRouter();

import "@xc-components/xc-form/lib/style.css";
import "@xc-components/xc-table/lib/style.css";

defineOptions({
  name: "UserView",
  components: { AddDialog }
});
const queryFormRef = ref<XcFormInstance>();
const query = ref({ pageIndex: 1, pageSize: 30, keyword: "", roleType: null });
const state = ref<"loading" | "error" | "">("");
const total = ref(0);
const tableConfig: TableConfig<UserItem>[] = [
  { label: "用户ID", prop: "id", hidden: true },
  { label: "用户名", prop: "name" },
  { label: "账号", prop: "account" },
  { label: "角色", prop: "role" }
];
const tableData = ref<UserItem[]>([]);
const queryFilterConfig: FormConfig[] = [
  { placeholder: "关键字搜索", prop: "keyword", attrs: { suffixIcon: Search } },
  { placeholder: "请选择角色", prop: "roleType", type: "select", options: [] }
];
const roles = ref<OptionItem[]>([]); // 角色列表

onMounted(() => {
  console.log("加载成功之后应该会触发这个函数");
  getRoleList();
  getList();
  // getMethodDescription(); // 获取接口参数说明
});
// onActivated(() => {
//   getList();
// });

/**
 * @description: 获取用户列表
 */
const getList = async () => {
  state.value = "loading";
  const {
    data: { list, total_Count }
  } = await getUsersByCondition(query.value);
  state.value = "";
  tableData.value = list || [];
  total.value = total_Count || 0;
};

/**
 * @description: 获取所有角色
 * @return {*}
 */
const getRoleList = async () => {
  const { data } = await getRoles({});
  roles.value = (data || []).map((it) => ({ label: it, value: it }));
  queryFormRef.value?.update("roleType", "options", roles.value);
};

/**
 * @description: 筛选
 * @return {*}
 */
let queryFilter = async ({ value, done }: { value: any; done: () => void }) => {
  query.value.pageIndex = 1;
  query.value = { ...query.value, ...value, roleType: value.roleType || null };
  await getList();
  done?.();
};

/**
 * @description: 编辑/新增
 * @return {*}
 */
const detailModel = (function useDetail() {
  const formDialogVisible = ref(false);
  const activeItem = ref<UserItem>();

  return {
    activeItem,
    formVisible: formDialogVisible,
    showForm: (item?: UserItem) => {
      activeItem.value = item;
      formDialogVisible.value = true;
    },
    onFormUpdate: getList
  };
})();
/**
 * @description: 删除
 * @param {*} id
 * @return {*}
 */
const onDelete = async (row: UserItem) => {
  await ElMessageBox({
    title: "提示",
    message: `是否确定删除用户“${row.name}”?`,
    type: "warning",
    showCancelButton: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = `执行中...`;
          await deleteUser({ userId: row.id });
          done();
        } catch {
          instance.confirmButtonText = `确定`;
        }
        instance.confirmButtonLoading = false;
      } else {
        done();
      }
    }
  });
  ElMessage.closeAll();
  ElMessage.success(`删除成功`);
  getList();
};

</script>

<style lang="scss" scoped>
.list-view {
  padding: 12px;
}
</style>
